using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;

namespace Nirvana
{
    public static class TimeUtils 
    {
        //private static DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));

        private static StringBuilder stringGetSecond3String = new StringBuilder();

        private static StringBuilder stringGetSecond2String = new StringBuilder();

        /// <summary>
        /// 检测是否新的一天
        /// </summary>
        public static bool CheckIsTomorrow(DateTime time)
        {
            if (time.Year == ServerDateTime.Year && time.Month == ServerDateTime.Month && time.Day == ServerDateTime.Day)
            {
                return false;
            }
            if (DateTime.Compare(time, ServerDateTime) < 0)
            {
                return true;
            }
            return false;
        }
        /// <summary>
        /// 获取N天后凌晨到当前时间的秒数
        /// </summary>
        /// <param name="day"></param>
        /// <returns></returns>
        public static int GetSecondToDayMidNight(int day)
        {
            TimeSpan ts = Convert.ToDateTime(ServerDateTime.AddDays(day).ToString("D").ToString()) - ServerDateTime;
            return Convert.ToInt32(ts.TotalSeconds);
        }
        /// <summary>
        /// 获取每日日期
        /// </summary>
        /// <returns></returns>
        public static int GetDayNum()
        {
            DateTime dt = ServerDateTime;
            return dt.Year * 10000 + dt.Month * 100 + dt.Day;
        }

        /// <summary>
        /// 毫秒时间转换格式
        /// </summary>
        /// <param name="Milliseconds">时间，ms</param>
        /// <param name="format"></param>
        /// <returns></returns>
        public static string TimeFormat(long Milliseconds, string format = "hh:mm:ss")
        {
            string result = "";

            int nH = (int)(Milliseconds / 1000 / 60 / 60);
            string hh = (nH).ToString();
            int nM = (int)((Milliseconds - nH * 1000 * 60 * 60) / 1000 / 60);
            string mm = (nM).ToString();
            float nS = Milliseconds / 1000f - ((int)(Milliseconds / 1000f / 60)) * 60f;
            string ss = (nS).ToString();

            if (format == "hh:mm:ss")
            {
                result = string.Format("{0}时 {1}分 {2}秒", hh, mm, ss);
            }
            else
            {
                result = string.Format("{0}秒", (Milliseconds / 1000f).ToString());
            }

            return result;
        }

        //获得当前时间
        public static DateTime ServerDateTime
        {
            get
            {
                long nowServerTime = GetLocalTime(); //UserData.Inst.GetServerNowTime();
                var date = ConvertToDateTime(nowServerTime);
                if (date.Year == 0001) date = LocalTime; //无法获取正确时间时
                return date;
            }
        }
        /// <summary>
        /// 通过时间戳(毫秒)获取本地时间
        /// </summary>
        /// <param name="timpStamp"></param>
        /// <returns></returns>
        public static DateTime GetLocalTimeByStamp(long timpStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));
            return dtStart.AddMilliseconds(timpStamp).ToLocalTime();
        }

        public static DateTime LocalTime
        {
            get
            {
                long time = GetLocalTime();
                return ConvertToDateTime(time);
            }
        }

        /// <summary>
        /// 当前时间戳（单位秒）
        /// </summary>
        /// <returns></returns>
        public static long GetLocalTime()
        {
            return Convert.ToInt64((DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalSeconds);
        }
        /// <summary>
        /// 秒时间转换格式
        /// </summary>
        /// <param name="second"></param>
        /// <returns></returns>
        public static string GetSecond3String(long second)
        {
            stringGetSecond3String.Remove(0, stringGetSecond3String.Length);
            stringGetSecond3String.AppendFormat("{0:D2}:{1:D2}:{2:D2}", second / 3600, second % 3600 / 60, second % 60);
            return stringGetSecond3String.ToString();
        }

        public static string GetSecond2String(int second)
        {
            stringGetSecond2String.Length = 0;
            stringGetSecond2String.AppendFormat("{0:D2}:{1:D2}", second / 60, second % 60);
            return stringGetSecond2String.ToString();
        }

        /// <summary>
        /// 时间格式转换为总秒数
        /// </summary>
        public static int GetString2Second(string times)
        {
            int totalSecond = 0;
            var _times = times.Split(':');
            if (_times != null)
            {
                if (_times.Length == 1)
                {
                    totalSecond = Convert.ToInt32(_times[0]);
                }
                else if (_times.Length == 2)
                {
                    totalSecond += Convert.ToInt32(_times[0]) * 60;
                    totalSecond += Convert.ToInt32(_times[1]);
                }
                else if (_times.Length == 3)
                {
                    totalSecond += Convert.ToInt32(_times[0]) * 60 * 60;
                    totalSecond += Convert.ToInt32(_times[1]) * 60;
                    totalSecond += Convert.ToInt32(_times[2]);
                }
            }
            else
            {
                totalSecond = Convert.ToInt32(times);
            }

            return totalSecond;
        }

        public static TimeSpan GetTime(long second)
        {
            return new TimeSpan(second * 1000 * 10000);
        }

        public static DateTime ConvertToDateTime(string timestamp)
        {
            DateTime time = DateTime.MinValue;
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));
            if (timestamp.Length == 10)        //精确到秒
            {
                time = startTime.AddSeconds(double.Parse(timestamp));
            }
            else if (timestamp.Length == 13)   //精确到毫秒
            {
                time = startTime.AddMilliseconds(double.Parse(timestamp));
            }
            return time;
        }

        /// <summary>
        /// 把linux时间转换为时间数据
        /// </summary>
        public static DateTime ConvertToDateTime(long d)
        {
            DateTime time = DateTime.MinValue;
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));
            string timestamp = d.ToString();
            if (timestamp.Length == 10)        //精确到秒
            {
                time = startTime.AddSeconds(d);
            }
            else if (timestamp.Length == 13)   //精确到毫秒
            {
                time = startTime.AddMilliseconds(d);
            }
            return time;
        }

        /// <summary>
        /// 把时间数据转换为linux格式：秒数
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static double ConvertDateTime2Second(DateTime time)
        {
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));
            return (time - startTime).TotalSeconds;
        }

        /// <summary>
        /// 把时间数据转换为linux格式：毫秒数
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static double ConvertDateTime2Millisecond(DateTime time)
        {
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));
            return (time - startTime).TotalMilliseconds;
        }

        public static long DateTimeToUnixTimestamp(DateTime dateTime, bool milliseconds = true)
        {
            DateTime d = new DateTime(1970, 1, 1, 0, 0, 0, dateTime.Kind);
            if (milliseconds)
            {
                return Convert.ToInt64((dateTime - d).TotalMilliseconds);
            }
            return Convert.ToInt64((dateTime - d).TotalSeconds);
        }

        public static DateTime UnixTimestampToDateTime(DateTime target, long timestamp)
        {
            return new DateTime(1970, 1, 1, 0, 0, 0, target.Kind).AddSeconds(timestamp);
        }
    }
}

